<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入用户姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="用户性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择用户性别" clearable>
          <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="humanresourceList" @selection-change="handleSelectionChange">
      <el-table-column label="用户姓名" align="center" prop="nickName">
        <template #default="scope">
          <el-button style="background-color: #5080e7; color: white; border: 1px solid #5080e7;" link
            @click="showLeader(scope.row)">{{ scope.row.nickName }}</el-button>
          <el-dialog v-model="leadershipData" title="用户上下级关系" v-if="leaderflag" :close-on-click-modal="false"
            :show-close="false">
            <div>
              <p><b>上级领导:</b> {{ leadershipData.leaderNickName }}</p>
              <b>下属姓名:</b><p v-for="(nickName, index) in leadershipData.subordinateNickName" :key="index"> {{ nickName }}</p>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closeLeader">关闭</el-button>
            </span>
          </el-dialog>
        </template>
      </el-table-column>
      <el-table-column label="用户性别" align="center" prop="sex">

        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="归属部门" align="center">

        <template v-slot="{ row }">
          {{ row.parentName }} / {{ row.deptName }}
        </template>
      </el-table-column>
      <el-table-column label="上级领导" align="center" prop="leaderNickName" />
      <el-table-column label="岗位" align="center" prop="postName" />
      <el-table-column label="工种" align="center" prop="roleName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:humanresource:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:humanresource:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改员工管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="humanresourceRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="form.nickName" placeholder="员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择用户性别" clearable>
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工ID" prop="userId">
              <el-input v-model="form.userId" placeholder="员工ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="nation">
              <el-input v-model="form.nation" placeholder="请输入民族" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24">
          <el-form-item label-width="82px" label="身份证号" prop="staffNumber">
            <el-input v-model="form.staffNumber" placeholder="身份证号" clearable :style="{ width: '100%' }" maxlength="18"
              oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0})?.*$/,'$1')"></el-input>
          </el-form-item>
          <el-form-item label-width="82px" label="手机号" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="手机号" clearable :style="{ width: '100%' }" maxlength="11"
              oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0})?.*$/,'$1')"></el-input>
          </el-form-item>
          <el-form-item label-width="82px" label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="邮箱" clearable :style="{ width: '100%' }"></el-input>
          </el-form-item>
          <el-form-item label-width="82px" label="银行卡号" prop="cardNumber">
            <el-input v-model="form.cardNumber" placeholder="银行卡号" clearable :style="{ width: '100%' }" maxlength="19"
              oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,0})?.*$/,'$1')"></el-input>
          </el-form-item>
        </el-col>
        <el-row>
          <el-col :span="12">
            <el-form-item label-width="82px" label="部门" prop="deptId">
              <el-tree-select v-model="form.deptId" :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门"
                check-strictly @nodes-click="handleNodeClick" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" label-width="50px">
              <el-select v-model="form.postIds" multiple placeholder="请选择">
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                  :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-width="82px" label="上级领导" prop="leaderNickName">
              <el-input v-model="form.leaderNickName" placeholder="上级领导" clearable
                :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工种" prop="roleId">
              <el-select v-model="form.roleName" placeholder="工种">
                <el-option v-for="dict in roleOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工价" prop="wages">
              <el-input v-model="form.wages" placeholder="单位：元每小时" maxlength="6"
                oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="12">
          <el-form-item label-width="78px" label="借支权限" prop="flag">
            <el-switch v-model="form.flag" active-text="允许" inactive-text="禁止" :active-value="1" :inactive-value="2"
              @change="borrowingFlagChange"></el-switch>
          </el-form-item>
        </el-col>
        <el-form :model="data" size="medium" label-width="80px" v-if="form.flag == 1">
          <el-row>
            <el-col :span="12">
              <el-form-item label-width="78px" label="可借金额" prop="amount">
                <el-input v-model="form.amount" placeholder="单位：元" clearable :style="{ width: '100%' }" maxlength="5"
                  oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/,'$1')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="78px" label="可借次数" prop="number">
                <el-input v-model="form.number" placeholder="请输入可借次数" clearable :style="{ width: '100%' }" maxlength="1"
                  oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0})?.*$/,'$1')"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Humanresource">
import { listHumanresource, getHumanresource, delHumanresource, addHumanresource, updateHumanresource } from "@/api/manage/humanresource";
import { deptTreeSelect, getUser } from "@/api/system/user";
import { show } from "@/api/manage/LandR";
import { getBorrowing } from "@/api/manage/borrowing";
import { computed } from "vue";


const { proxy } = getCurrentInstance();
const { flag, sys_user_sex } = proxy.useDict('flag', 'sys_user_sex');

const borrowingFlag = ref(false);
const postOptions = ref([]);
const deptOptions = ref(undefined);
const humanresourceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const leadershipData = ref([]);

const roleOptions = [
  { label: "正式员工", value: 3 },
  { label: "小时工", value: 4 },
]

const borrowingFlagChange = (value) => {
  // 1表示允许借支
  if (value == 1) {
    borrowingFlag.value = true;
  } else {
    borrowingFlag.value = false;
  }
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: null,
    sex: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询员工管理列表 */
function getList() {
  loading.value = true;
  listHumanresource(queryParams.value).then(response => {
    humanresourceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    userName: null,
    nickName: null,
    userType: null,
    email: null,
    phonenumber: null,
    sex: null,
    avatar: null,
    password: null,
    status: null,
    delFlag: null,
    loginIp: null,
    loginDate: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    level: null,
    idleState: null,
    deptId: null,
    staffNumber: null,
    nation: null,
    wages: null,
    flag: null,
    cardNumber: null,
    deptName: null,
    postId: null,
    roleId: null,
    postName: null,
    roleName: null,
    amount: null,
    number: null,
    postIds: [],
    parentName: null,
    leaderNickName: null
  };
  proxy.resetForm("humanresourceRef");
}

/** 关闭窗口 */
let leaderflag = ref(false);
function closeLeader() {
  leaderflag.value = false
  leadershipData = ref([]);
}

/** 查询用户上下级关系 */
function showLeader(val) {
  leaderflag.value = true
  let userId = parseInt(val.userId, 10)
  show(userId).then(response => {
    leadershipData.value = response.data;
    console.log("leadershipData.value:" + response.data);

  });


}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getUser(row.userId).then(response => {
    postOptions.value = response.posts;
    form.value.postIds = response.postIds;
  });
  const _userId = row.userId || ids.value
  getHumanresource(_userId).then(response => {
    form.value = response.data;
    getBorrowing(row.userId).then(response => {
      form.value.amount = response.data.amount;
      form.value.number = response.data.number;
    })
    open.value = true;
    title.value = "修改员工管理";
  });

}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["humanresourceRef"].validate(valid => {
    if (valid) {
      if (form.value.userId != null) {
        form.value.roleId = form.value.roleName
        if (typeof form.value.roleId == "string") {
          form.value.roleId = null
        }
        updateHumanresource(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addHumanresource(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _userIds = row.userId || ids.value;
  proxy.$modal.confirm('是否确认删除员工管理编号为"' + _userIds + '"的数据项？').then(function () {
    return delHumanresource(_userIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

getDeptTree();
getList();
</script>
